home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 January, February, March & April / Chip-Cover-CD-2007-02.iso / Pakiet bezpieczenstwa / mini Pentoo LiveCD 2006.1 / mpentoo-2006.1.iso / livecd.squashfs / usr / lib / portage / bin / repoman < prev    next >
Encoding:
Text File  |  2006-06-30  |  59.8 KB  |  1,739 lines

  1. #!/usr/bin/python -O
  2. # Copyright 1999-2006 Gentoo Foundation
  3. # Distributed under the terms of the GNU General Public License v2
  4. # $Id: /var/cvsroot/gentoo-src/portage/bin/repoman,v 1.98.2.23 2005/06/18 01:00:43 vapier Exp $
  5.  
  6. # Next to do: dep syntax checking in mask files
  7. # Then, check to make sure deps are satisfiable (to avoid "can't find match for" problems)
  8. # that last one is tricky because multiple profiles need to be checked.
  9.  
  10. import os,sys,shutil
  11. if not hasattr(__builtins__, "set"):
  12.     from sets import Set as set
  13. exename=os.path.basename(sys.argv[0])    
  14. os.environ["PORTAGE_CALLER"]="repoman"
  15. sys.path = ["/usr/lib/portage/pym"]+sys.path
  16. version="1.2"    
  17.  
  18. allowed_filename_chars="a-zA-Z0-9._-+:"
  19. allowed_filename_chars_set = {}
  20. map(allowed_filename_chars_set.setdefault, map(chr, range(ord('a'), ord('z')+1)))
  21. map(allowed_filename_chars_set.setdefault, map(chr, range(ord('A'), ord('Z')+1)))
  22. map(allowed_filename_chars_set.setdefault, map(chr, range(ord('0'), ord('9')+1)))
  23. map(allowed_filename_chars_set.setdefault, map(chr, map(ord, [".", "-", "_", "+", ":"])))
  24.  
  25. import string,signal,re,pickle,tempfile
  26.  
  27. import portage
  28. import portage_checksum
  29. import portage_const
  30. import portage_dep
  31. import portage_exception
  32. import cvstree
  33. import time
  34. import codecs
  35.  
  36. from portage_manifest import Manifest
  37.  
  38. from output import *
  39. #bold, darkgreen, darkred, green, red, turquoise, yellow
  40.  
  41. from commands import getstatusoutput
  42. from fileinput import input
  43. from grp import getgrnam
  44. from stat import *
  45.  
  46. if portage.settings["NOCOLOR"] in ("yes","true") or not sys.stdout.isatty():
  47.     nocolor()
  48.  
  49. def warn(txt):
  50.     print exename+": "+txt
  51. def err(txt):
  52.     warn(txt)
  53.     sys.exit(1)
  54.  
  55. def err_help(txt):
  56.     help(exitstatus=-1,helpfulness=0)
  57.     warn(txt)
  58.     sys.exit(1)
  59.  
  60. def exithandler(signum=None,frame=None):
  61.     sys.stderr.write("\n"+exename+": Interrupted; exiting...\n")
  62.     sys.exit(1)
  63.     os.kill(0,signal.SIGKILL)
  64. signal.signal(signal.SIGINT,exithandler)
  65.  
  66. REPOROOTS=["gentoo-x86"]
  67. shortmodes={"ci":"commit"}
  68. modeshelp={
  69. "scan"   : "Scan directory tree for QA issues (default)",
  70. "fix"    : "Fix simple QA issues (stray digests, missing digests)",
  71. "full"   : "Scan directory tree for QA issues (full listing)",
  72. "help"   : "Show this screen",
  73. "commit" : "Scan directory tree for QA issues; if OK, commit via cvs",
  74. "last"   : "Remember report from last run",
  75. "lfull"  : "Remember report from last run (full listing)"
  76. }
  77. modes=modeshelp.keys()
  78. repoman_options={
  79. "--commitmsg"      : "Adds a commit message via the command line",
  80. "--commitmsgfile"  : "Adds a commit message from the specified file",
  81. "--help"           : "Show this screen",
  82. "--ignore-arches"  : "Ignore arch-specific failures (where arch != host)",
  83. "--ignore-masked"  : "Ignore masked packages (not allowed with commit mode)",
  84. "--pretend"        : "Don't commit or fix anything; just show what would be done",
  85. "--quiet"          : "Be less verbose about extraneous info",
  86. "--verbose"        : "Displays every package name while checking",
  87. "--version"        : "Show version info",
  88. "--xmlparse"       : "Forces the metadata.xml parse check to be carried out"
  89. }
  90. repoman_shortoptions={
  91. "-h" : "--help",
  92. "-i" : "--ignore-masked",
  93. "-I" : "--ignore-arches",
  94. "-m" : "--commitmsg",
  95. "-M" : "--commitmsgfile",
  96. "-p" : "--pretend",
  97. "-q" : "--quiet",
  98. "-v" : "--verbose",
  99. "-V" : "--version",
  100. "-x" : "--xmlparse"
  101. }
  102. repoman_shortoptions_rev=dict([(v,k) for (k,v) in repoman_shortoptions.items()])
  103. options=repoman_options.keys()
  104.  
  105. qahelp={
  106.     "CVS/Entries.IO_error":"Attempting to commit, and an IO error was encountered access the Entries file",
  107.     "digest.partial":"Digest files do not contain all corresponding URI elements",
  108.     "digest.assumed":"Existing digest must be assumed correct (Package level only)",
  109.     "digestentry.unused":"Digest/Manifest entry has no matching SRC_URI entry",
  110.     "digest.fail":"Digest does not match the specified local file",
  111.     "digest.stray":"Digest files that do not have a corresponding ebuild",
  112.     "digest.missing":"Digest files that are missing (ebuild exists, digest doesn't)",
  113.     "digest.disjointed":"Digests not added to cvs when the matching ebuild has been added",
  114.     "digest.notadded":"Digests that exist but have not been added to cvs",
  115.     "digest.unmatch":"Digests which are incomplete (please check if your USE/ARCH includes all files)",
  116.     "ebuild.invalidname":"Ebuild files with a non-parseable or syntactically incorrect name (or using 2.1 versioning extensions)",
  117.     "ebuild.namenomatch":"Ebuild files that do not have the same name as their parent directory",
  118.     "changelog.missing":"Missing ChangeLog files",
  119.     "ebuild.disjointed":"Ebuilds not added to cvs when the matching digest has been added",
  120.     "ebuild.notadded":"Ebuilds that exist but have not been added to cvs",
  121.     "changelog.notadded":"ChangeLogs that exist but have not been added to cvs",
  122.     "filedir.missing":"Package lacks a files directory",
  123.     "file.executable":"Ebuilds, digests, metadata.xml, Manifest, and ChangeLog do note need the executable bit",
  124.     "file.size":"Files in the files directory must be under 20k",
  125.     "file.name":"File/dir name must be composed of only the following chars: %s " % allowed_filename_chars,
  126.     "file.UTF8":"File is not UTF8 compliant",
  127.     "KEYWORDS.missing":"Ebuilds that have a missing or empty KEYWORDS variable",
  128.     "KEYWORDS.stupid":"Ebuilds that use KEYWORDS=-* instead of package.mask", 
  129.     "LICENSE.missing":"Ebuilds that have a missing or empty LICENSE variable",
  130.     "DESCRIPTION.missing":"Ebuilds that have a missing or empty DESCRIPTION variable",
  131.     "SLOT.missing":"Ebuilds that have a missing or empty SLOT variable",
  132.     "HOMEPAGE.missing":"Ebuilds that have a missing or empty HOMEPAGE variable",
  133.     "DEPEND.bad":"User-visible ebuilds with bad DEPEND settings (matched against *visible* ebuilds)",
  134.     "RDEPEND.bad":"User-visible ebuilds with bad RDEPEND settings (matched against *visible* ebuilds)",
  135.     "PDEPEND.bad":"User-visible ebuilds with bad PDEPEND settings (matched against *visible* ebuilds)",
  136.     "DEPEND.badmasked":"Masked ebuilds with bad DEPEND settings (matched against *all* ebuilds)",
  137.     "RDEPEND.badmasked":"Masked ebuilds with RDEPEND settings (matched against *all* ebuilds)",
  138.     "PDEPEND.badmasked":"Masked ebuilds with PDEPEND settings (matched against *all* ebuilds)",
  139.     "DEPEND.badindev":"User-visible ebuilds with bad DEPEND settings (matched against *visible* ebuilds) in developing arch",
  140.     "RDEPEND.badindev":"User-visible ebuilds with bad RDEPEND settings (matched against *visible* ebuilds) in developing arch",
  141.     "PDEPEND.badindev":"User-visible ebuilds with bad PDEPEND settings (matched against *visible* ebuilds) in developing arch",
  142.     "DEPEND.badmaskedindev":"Masked ebuilds with bad DEPEND settings (matched against *all* ebuilds) in developing arch",
  143.     "RDEPEND.badmaskedindev":"Masked ebuilds with RDEPEND settings (matched against *all* ebuilds) in developing arch",
  144.     "PDEPEND.badmaskedindev":"Masked ebuilds with PDEPEND settings (matched against *all* ebuilds) in developing arch",
  145.     "DEPEND.syntax":"Syntax error in DEPEND (usually an extra/missing space/parenthesis)",
  146.     "RDEPEND.syntax":"Syntax error in RDEPEND (usually an extra/missing space/parenthesis)",
  147.     "PDEPEND.syntax":"Syntax error in PDEPEND (usually an extra/missing space/parenthesis)",
  148.     "LICENSE.syntax":"Syntax error in LICENSE (usually an extra/missing space/parenthesis)",
  149.     "PROVIDE.syntax":"Syntax error in PROVIDE (usually an extra/missing space/parenthesis)",
  150.     "ebuild.syntax":"Error generating cache entry for ebuild; typically caused by ebuild syntax error",
  151.     "ebuild.output":"A simple sourcing of the ebuild produces output; this breaks ebuild policy.",
  152.     "ebuild.nesteddie":"Placing 'die' inside ( ) prints an error, but doesn't stop the ebuild.",
  153.     "variable.readonly":"Assigning a readonly variable",
  154.     "LIVEVCS.stable":"This ebuild is a live checkout from a VCS but has stable keywords.",
  155.     "IUSE.invalid":"This ebuild has a variable in IUSE that is not in the use.desc or use.local.desc file",
  156.     "LICENSE.invalid":"This ebuild is listing a license that doesnt exist in portages license/ dir.",
  157.     "KEYWORDS.invalid":"This ebuild contains KEYWORDS that are not listed in profiles/arch.list or for which no valid profile was found",
  158.     "ebuild.nostable":"There are no ebuilds that are marked as stable for your ARCH",
  159.     "ebuild.allmasked":"All ebuilds are masked for this package (Package level only)",
  160.     "ebuild.majorsyn":"This ebuild has a major syntax error that may cause the ebuild to fail partially or fully",
  161.     "ebuild.minorsyn":"This ebuild has a minor syntax error that contravenes gentoo coding style",
  162.     "ebuild.badheader":"This ebuild has a malformed header",
  163.     "metadata.missing":"Missing metadata.xml files",
  164.     "metadata.bad":"Bad metadata.xml files",
  165.     "virtual.versioned":"PROVIDE contains virtuals with versions",
  166.     "virtual.exists":"PROVIDE contains existing package names",
  167.     "virtual.unavailable":"PROVIDE contains a virtual which contains no profile default",
  168.     "usage.obsolete":"The ebuild makes use of an obsolete construct"
  169. }
  170.  
  171. qacats = qahelp.keys()
  172. qacats.sort()
  173.  
  174. qawarnings=[
  175. "changelog.missing",
  176. "changelog.notadded",
  177. "ebuild.notadded",
  178. "ebuild.nostable",
  179. "ebuild.allmasked",
  180. "ebuild.nesteddie",
  181. "digest.assumed",
  182. "digest.notadded",
  183. "digest.disjointed",
  184. "digest.missing",
  185. "digestentry.unused",
  186. "DEPEND.badmasked","RDEPEND.badmasked","PDEPEND.badmasked",
  187. "DEPEND.badindev","RDEPEND.badindev","PDEPEND.badindev",
  188. "DEPEND.badmaskedindev","RDEPEND.badmaskedindev","PDEPEND.badmaskedindev",
  189. "IUSE.invalid",
  190. "KEYWORDS.stupid",
  191. "ebuild.minorsyn",
  192. "ebuild.badheader",
  193. "file.size",
  194. "metadata.missing",
  195. "metadata.bad",
  196. "virtual.versioned",
  197. "virtual.exists",
  198. "virtual.unavailable",
  199. "usage.obsolete",
  200. "LIVEVCS.stable"
  201. ]
  202.  
  203. missingvars=["KEYWORDS","LICENSE","DESCRIPTION","HOMEPAGE","SLOT"]
  204. allvars=portage.auxdbkeys
  205. commitmessage=None
  206. commitmessagefile=None
  207. for x in missingvars:
  208.     x += ".missing"
  209.     if x not in qacats:
  210.         print "* missingvars values need to be added to qahelp ("+x+")"
  211.         qacats.append(x)
  212.         qawarnings.append(x)
  213.  
  214.  
  215. ven_cat = r'[\w0-9-]+'                                 # Category
  216. ven_nam = r'([+a-z0-9-]+(?:[+_a-z0-9-]*[+a-z0-9-]+)*)' # Name
  217. ven_ver = r'((?:\d+\.)*\d+[a-z]?)'                     # Version
  218. ven_suf = r'(_(alpha\d*|beta\d*|pre\d*|rc\d*|p\d+))?'  # Suffix
  219. ven_rev = r'(-r\d+)?'                                  # Revision
  220.     
  221. ven_string=ven_cat+'/'+ven_nam+'-'+ven_ver+ven_suf+ven_rev
  222. valid_ebuild_name_re=re.compile(ven_string+'$', re.I)
  223. valid_ebuild_filename_re=re.compile(ven_string+'\.ebuild$', re.I)
  224.  
  225. repoman_settings = portage.config(clone=portage.settings)
  226. verbose=0
  227. quiet=0
  228.  
  229. def valid_ebuild_name(name):
  230.     """(name) --- Checks to ensure that the package name meets portage specs.
  231.     Return 1 if valid, 0 if not."""
  232.     # Handle either a path to the ebuild, or cat/pkg-ver string
  233.     if (len(name) > 7) and (name[-7:] == ".ebuild"):
  234.         if valid_ebuild_filename_re.match(name):
  235.             return 1
  236.     else:
  237.         if valid_ebuild_name_re.match(name):
  238.             return 1
  239.     return 0
  240.  
  241.  
  242. def show_version():
  243.     print exename+" "+version
  244.     sys.exit(0)
  245.     
  246. def help(exitstatus=1,helpfulness=1):
  247.     if quiet:
  248.         helpfulness=0
  249.     if helpfulness:
  250.         print
  251.         print green(exename+" "+version)
  252.         print " \"Quality is job zero.\""
  253.         print " Copyright 1999-2006 Gentoo Foundation"
  254.         print " Distributed under the terms of the GNU General Public License v2"
  255.         print
  256.     print bold(" Usage:"),turquoise(exename),"[",green("options"),"] [",green("mode"),"]"
  257.     if helpfulness:
  258.         print bold(" Modes:"),turquoise("scan (default)"),
  259.         for x in modes[1:]:
  260.             print "|",turquoise(x),
  261.         print
  262.     print
  263.     print " "+green(string.ljust("Options",20)+" Description")
  264.     for x in options:
  265.         if repoman_shortoptions_rev.has_key(x):
  266.             shopt=repoman_shortoptions_rev[x]+", "+x
  267.         else:
  268.             shopt="    "+x
  269.         print " "+string.ljust(shopt,20),repoman_options[x]
  270.     print
  271.     print " "+green(string.ljust("Modes",20)+" Description")
  272.     for x in modes:
  273.         print " "+string.ljust(x,20),modeshelp[x]
  274.     if helpfulness:
  275.         print
  276.         print " "+green(string.ljust("QA keyword",20)+" Description")
  277.         for x in qacats:
  278.             print " "+string.ljust(x,20),qahelp[x]
  279.         print
  280.     if (exitstatus != -1):
  281.         sys.exit(exitstatus)
  282.     else:
  283.         print
  284.  
  285. def last():
  286.     try:
  287.         #Retrieve and unpickle stats and fails from saved files
  288.         savedf=open('/var/cache/edb/repo.stats','r')
  289.         stats = pickle.load(savedf)
  290.         savedf.close()
  291.         savedf=open('/var/cache/edb/repo.fails','r')
  292.         fails = pickle.load(savedf)
  293.         savedf.close()
  294.     except SystemExit, e:
  295.         raise  # Need to propogate this
  296.     except:
  297.         err("Error retrieving last repoman run data; exiting.")
  298.  
  299.     #dofail will be set to 1 if we have failed in at least one non-warning category
  300.     dofail=0
  301.     #dowarn will be set to 1 if we tripped any warnings
  302.     dowarn=0
  303.     #dofull will be set if we should print a "repoman full" informational message
  304.     dofull=0
  305.  
  306.     print
  307.     print green("RepoMan remembers...")
  308.     print
  309.     for x in qacats:
  310.         if stats[x]:
  311.             dowarn=1
  312.             if x not in qawarnings:
  313.                 dofail=1
  314.         else:
  315.             if mymode!="lfull":
  316.                 continue
  317.         print "  "+string.ljust(x,20),
  318.         if stats[x]==0:
  319.             print green(`stats[x]`)
  320.             continue
  321.         elif x in qawarnings:
  322.             print yellow(`stats[x]`)
  323.         else:
  324.             print red(`stats[x]`)
  325.         if mymode!="lfull":
  326.             if stats[x]<12:
  327.                 for y in fails[x]:
  328.                     print "   "+y
  329.             else:
  330.                 dofull=1
  331.         else:
  332.             for y in fails[x]:
  333.                 print "   "+y
  334.     print
  335.     if dofull:
  336.         print bold("Note: type \"repoman lfull\" for a complete listing of repomans last run.")
  337.         print
  338.     if dowarn and not dofail:
  339.         print green("RepoMan sez:"),"\"You only gave me a partial QA payment last time?\n              I took it, but I wasn't happy.\""
  340.     elif not dofail:
  341.         print green("RepoMan sez:"),"\"If everyone were like you, I'd be out of business!\""
  342.     print
  343.     sys.exit(1)
  344.  
  345. mymode=None
  346. myoptions=[]
  347. if len(sys.argv)>1:
  348.     x=1
  349.     while x < len(sys.argv):
  350.         if sys.argv[x] in shortmodes.keys():
  351.             sys.argv[x]=shortmodes[sys.argv[x]]
  352.         elif sys.argv[x] in repoman_shortoptions.keys():
  353.             sys.argv[x] = repoman_shortoptions[sys.argv[x]]
  354.         if sys.argv[x] in modes:
  355.             if mymode is None:
  356.                 mymode=sys.argv[x]
  357.             else:
  358.                 err("Please specify either \""+mymode+"\" or \""+sys.argv[x]+"\", but not both.")
  359.         elif sys.argv[x] in options:
  360.             optionx=sys.argv[x]
  361.             if (optionx=="--commitmsg") and (len(sys.argv)>=(x+1)):
  362.                 commitmessage=sys.argv[x+1]
  363.                 x=x+1
  364.             elif (optionx=="--commitmsgfile") and (len(sys.argv)>=(x+1)):
  365.                 commitmessagefile=sys.argv[x+1]
  366.                 x=x+1
  367.             elif (optionx=="--verbose"):
  368.                 verbose+=1
  369.             elif (optionx=="--quiet"):
  370.                 quiet+=1
  371.             elif optionx not in myoptions:
  372.                 myoptions.append(optionx)
  373.         else:
  374.             err_help("\""+sys.argv[x]+"\" is not a valid mode or option.")
  375.         x=x+1
  376. if mymode is None:
  377.     mymode="scan"
  378. if mymode=="help" or ("--help" in myoptions):
  379.     help(exitstatus=0)
  380. if ("--version" in myoptions):
  381.     show_version()
  382. if mymode=="last" or (mymode=="lfull"):
  383.     last()
  384. if mymode == "commit":
  385.     while "--ignore-masked" in myoptions:
  386.         myoptions.remove("--ignore-masked")
  387.  
  388. isCvs=False
  389. myreporoot=None
  390. if os.path.isdir("CVS"):
  391.     repoman_settings["PORTDIR_OVERLAY"]=""
  392.     if "cvs" not in repoman_settings.features:
  393.         print
  394.         print
  395.         print red('!!! You do not have ')+bold('FEATURES="cvs" ')+red("enabled...")
  396.         print red("!!! ")+bold("Adding \"cvs\" to FEATURES")
  397.         print
  398.         os.environ["FEATURES"]=repoman_settings["FEATURES"]+" cvs"
  399.  
  400.     try:
  401.         isCvs=True
  402.         myrepofile=open("CVS/Repository")
  403.         myreporoot=myrepofile.readline()[:-1]
  404.         myrepofile.close()
  405.         myrepofile=open("CVS/Root")
  406.         myreporootpath=string.split(myrepofile.readline()[:-1], ":")[-1]
  407.         myrepofile.close()
  408.         if myreporootpath == myreporoot[:len(myreporootpath)]:
  409.             # goofy os x cvs co.
  410.             myreporoot = myreporoot[len(myreporootpath):]
  411.             while myreporoot and myreporoot[0] == '/':
  412.                 myreporoot = myreporoot[1:]
  413.     except (OSError, IOError):
  414.         err("Error grabbing repository information; exiting.")
  415.  
  416. if not "--pretend" in myoptions and not isCvs:
  417.     print
  418.     print darkgreen("Not in a CVS repository; enabling pretend mode.")
  419.     myoptions.append("--pretend");
  420.  
  421.  
  422. def have_profile_dir(path, maxdepth=3):
  423.     while path != "/" and maxdepth:
  424.         if os.path.exists(path + "/profiles/package.mask"):
  425.             return path
  426.         path = os.path.normpath(path + "/..")
  427.         maxdepth -= 1
  428.  
  429. portdir=None
  430. portdir_overlay=None
  431. mydir=os.getcwd()
  432. if "PWD" in os.environ and os.environ["PWD"] != mydir and \
  433.     os.path.realpath(os.environ["PWD"]) == mydir:
  434.     # getcwd() returns the canonical path but that makes it hard for repoman to
  435.     # orient itself if the user has symlinks in their portage tree structure.
  436.     # We use os.environ["PWD"], if available, to get the non-canonical path of
  437.     # the current working directory (from the shell).
  438.     mydir = os.environ["PWD"]
  439. if mydir[-1] != "/":
  440.     mydir += "/"
  441.  
  442. for overlay in repoman_settings["PORTDIR_OVERLAY"].split():
  443.     if overlay[-1] != "/":
  444.         overlay += "/"
  445.     if mydir[:len(overlay)] == overlay:
  446.         portdir_overlay = overlay
  447.         subdir = mydir[len(overlay):]
  448.         if subdir and subdir[-1] != "/":
  449.             subdir += "/"
  450.         if have_profile_dir(mydir, subdir.count("/")):
  451.             portdir = portdir_overlay
  452.         break
  453.  
  454. if not portdir_overlay:
  455.     if (repoman_settings["PORTDIR"]+"/")[:len(mydir)] == mydir:
  456.         portdir_overlay = repoman_settings["PORTDIR"]
  457.     else:
  458.         portdir_overlay = have_profile_dir(mydir)
  459.     portdir = portdir_overlay
  460.  
  461. if not portdir_overlay:
  462.     print darkred("Unable to determine PORTDIR.")
  463.     sys.exit(1)
  464.  
  465. if not portdir:
  466.     portdir = repoman_settings["PORTDIR"]
  467.  
  468. if portdir[-1] == "/":
  469.     portdir = portdir[:-1]
  470. if portdir_overlay[-1] == "/":
  471.     portdir_overlay = portdir_overlay[:-1]
  472.  
  473. os.environ["PORTDIR"] = portdir
  474. if portdir_overlay != portdir:
  475.     os.environ["PORTDIR_OVERLAY"] = portdir_overlay
  476. else:
  477.     os.environ["PORTDIR_OVERLAY"] = ""
  478.  
  479. if quiet < 2:
  480.     print "\nSetting paths:"
  481.     print "PORTDIR = \""+os.environ["PORTDIR"]+"\""
  482.     print "PORTDIR_OVERLAY = \""+os.environ["PORTDIR_OVERLAY"]+"\""
  483.  
  484.  
  485. reload(portage)
  486. repoman_settings = portage.config(clone=portage.settings)
  487.  
  488. if not myreporoot:
  489.     myreporoot = os.path.basename(portdir_overlay)
  490.     myreporoot += mydir[len(portdir_overlay):-1]
  491.  
  492. if isCvs:
  493.     reporoot=None
  494.     for x in REPOROOTS:
  495.         if myreporoot[0:len(x)]==x:
  496.             reporoot=myreporoot
  497.     if not reporoot:
  498.         err("Couldn't recognize repository type.  Supported repositories:\n"+repr(REPOROOTS))
  499. reposplit=string.split(myreporoot,"/")
  500. repolevel=len(reposplit)
  501.  
  502. # check if it's in $PORTDIR/$CATEGORY/$PN , otherwise bail if commiting.
  503. # Reason for this is if they're trying to commit in just $FILESDIR/*, the Manifest needs updating.
  504. # this check ensure that repoman knows where it is, and the manifest recommit is at least possible.
  505. if mymode == "commit" and repolevel not in [1,2,3]:
  506.     print red("***")+" Commit attempts *must* be from within a cvs co, category, or package directory."
  507.     print red("***")+" Attempting to commit from a packages files directory will be blocked for instance."
  508.     print red("***")+" This is intended behaviour, to ensure the manifest is recommited for a package."
  509.     print red("***")
  510.     err("Unable to identify level we're commiting from for %s" % string.join(reposplit,'/'))
  511.  
  512. startdir=os.getcwd()
  513.  
  514. for x in range(0,repolevel-1):
  515.     os.chdir("..")
  516. repodir=os.getcwd()
  517. os.chdir(startdir)
  518.  
  519. def caterror(mycat):
  520.     err(mycat+" is not an official category.  Skipping QA checks in this directory.\nPlease ensure that you add "+catdir+" to "+repodir+"/profiles/categories\nif it is a new category.")
  521. if "--pretend" in myoptions:
  522.     print green("\nRepoMan does a once-over of the neighborhood...")
  523. elif quiet < 1:
  524.     print green("\nRepoMan scours the neighborhood...")
  525.  
  526. # retreive local USE list
  527. luselist={}
  528. try:
  529.     mylist=portage.grabfile(portdir+"/profiles/use.local.desc")
  530.     for mypos in range(0,len(mylist)):
  531.         mysplit=mylist[mypos].split()[0]
  532.         myuse=string.split(mysplit,":")
  533.         if len(myuse)==2:
  534.             if not luselist.has_key(myuse[0]):
  535.                 luselist[myuse[0]] = []
  536.             luselist[myuse[0]].append(myuse[1])
  537. except SystemExit, e:
  538.     raise  # Need to propogate this
  539. except:
  540.     err("Couldn't read from use.local.desc")
  541.  
  542. # setup a uselist from portage
  543. uselist=[]
  544. try:
  545.     uselist=portage.grabfile(portdir+"/profiles/use.desc")
  546.     for l in range(0,len(uselist)):
  547.         uselist[l]=string.split(uselist[l])[0]
  548.     for var in string.split(repoman_settings["USE_EXPAND"]):
  549.         vardescs = portage.grabfile(portdir+"/profiles/desc/"+var.lower()+".desc")
  550.         for l in range(0, len(vardescs)):
  551.             uselist.append(var.lower() + "_" + string.split(vardescs[l])[0])
  552. except SystemExit, e:
  553.     raise  # Need to propogate this
  554. except:
  555.     err("Couldn't read USE flags from use.desc")
  556.  
  557. # retrieve a list of current licenses in portage
  558. liclist=portage.listdir(portdir+"/licenses")
  559. if not liclist:
  560.     err("Couldn't find licenses?")
  561.  
  562. # retrieve list of offical keywords
  563. try:
  564.     kwlist=portage.grabfile(portdir+"/profiles/arch.list")
  565. except SystemExit, e:
  566.     raise  # Need to propogate this
  567. except:
  568.     err("Couldn't read KEYWORDS from arch.list")
  569. if not kwlist:
  570.     kwlist=["alpha","arm","hppa","mips","ppc","sparc","x86"]
  571.  
  572. scanlist=[]
  573. if repolevel==2:
  574.     #we are inside a category directory
  575.     catdir=reposplit[-1]
  576.     if catdir not in repoman_settings.categories:
  577.         caterror(catdir)
  578.     mydirlist=os.listdir(startdir)
  579.     for x in mydirlist:
  580.         if x=="CVS":
  581.             continue
  582.         if os.path.isdir(startdir+"/"+x):
  583.             scanlist.append(catdir+"/"+x)
  584. elif repolevel==1:
  585.     for x in repoman_settings.categories:
  586.         if not os.path.isdir(startdir+"/"+x):
  587.             continue
  588.         for y in os.listdir(startdir+"/"+x):
  589.             if y=="CVS":
  590.                 continue
  591.             if os.path.isdir(startdir+"/"+x+"/"+y):
  592.                 scanlist.append(x+"/"+y)
  593. elif repolevel==3:
  594.     catdir = reposplit[-2]
  595.     if catdir not in repoman_settings.categories:
  596.         caterror(catdir)
  597.     scanlist.append(catdir+"/"+reposplit[-1])
  598.  
  599. profiles={}
  600. descfile=portdir+"/profiles/profiles.desc"
  601. if os.path.exists(descfile):
  602.     for x in portage.grabfile(descfile):
  603.         if x[0]=="#":
  604.             continue
  605.         arch=string.split(x)
  606.         if len(arch)!=3:
  607.             print "wrong format: \""+red(x)+"\" in "+descfile
  608.             continue
  609.         if not os.path.isdir(portdir+"/profiles/"+arch[1]):
  610.             print "Invalid "+arch[2]+" profile ("+arch[1]+") for arch "+arch[0]
  611.             continue
  612.         if profiles.has_key(arch[0]):
  613.             profiles[arch[0]]+= [[arch[1], arch[2]]]
  614.         else:
  615.             profiles[arch[0]] = [[arch[1], arch[2]]]
  616.  
  617.     for x in repoman_settings.archlist():
  618.         if x[0] == "~":
  619.             continue
  620.         if not profiles.has_key(x):
  621.             print red("\""+x+"\" doesn't have a valid profile listed in profiles.desc.")
  622.             print red("You need to either \"cvs update\" your profiles dir or follow this")
  623.             print red("up with the "+x+" team.")
  624.             print
  625. else:
  626.     print red("profiles.desc does not exist: "+descfile)
  627.     print red("You need to do \"cvs update\" in profiles dir.")
  628.     print
  629.     sys.exit(1)
  630.  
  631.  
  632. stats={}
  633. fails={}
  634. #objsadded records all object being added to cvs
  635. objsadded=[]
  636. for x in qacats:
  637.     stats[x]=0
  638.     fails[x]=[]
  639. xmllint_capable = False
  640. if getstatusoutput('which xmllint')[0] != 0:
  641.     print red("!!! xmllint not found. Can't check metadata.xml.\n")
  642.     if "--xmlparse" in myoptions or repolevel==3:
  643.         print red("!!!")+" sorry, xmllint is needed.  failing\n"
  644.         sys.exit(1)
  645. else:
  646.     #hardcoded paths/urls suck. :-/
  647.     must_fetch=1
  648.     backup_exists=0
  649.     try:
  650.         # if it's been over a week since fetching (or the system clock is fscked), grab an updated copy of metadata.dtd 
  651.         # clock is fscked or it's been a week. time to grab a new one.
  652.         ct=os.stat(portage.CACHE_PATH + '/metadata.dtd')[ST_CTIME]
  653.         if abs(time.time() - ct) > (60*60*24*7):
  654.             # don't trap the exception, we're watching for errno 2 (file not found), anything else is a bug.
  655.             backup_exists=1
  656.         else:
  657.             must_fetch=0
  658.  
  659.     except (OSError,IOError), e:
  660.         if e.errno != 2:
  661.             print red("!!!")+" caught exception '%s' for %s/metadata.dtd, bailing" % (str(e), portage.CACHE_PATH)
  662.             sys.exit(1)
  663.  
  664.     if must_fetch:
  665.         print 
  666.         print green("***")+" the local copy of metadata.dtd needs to be refetched, doing that now"
  667.         print
  668.         try:
  669.             if os.path.exists(repoman_settings["DISTDIR"]+'/metadata.dtd'):
  670.                 os.remove(repoman_settings["DISTDIR"]+'/metadata.dtd')
  671.             val=portage.fetch(['http://www.gentoo.org/dtd/metadata.dtd'],repoman_settings,fetchonly=0, \
  672.                 try_mirrors=0)
  673.             if val:
  674.                 if backup_exists:
  675.                     os.remove(portage.CACHE_PATH+'/metadata.dtd')
  676.                 shutil.copy(repoman_settings["DISTDIR"]+'/metadata.dtd',portage.CACHE_PATH+'/metadata.dtd')
  677.                 os.chown(portage.CACHE_PATH+'/metadata.dtd',os.getuid(),portage.portage_gid)
  678.                 os.chmod(portage.CACHE_PATH+'/metadata.dtd',0664)
  679.  
  680.  
  681.         except SystemExit, e:
  682.             raise  # Need to propogate this
  683.         except Exception,e:
  684.             print
  685.             print red("!!!")+" attempting to fetch 'http://www.gentoo.org/dtd/metadata.dtd', caught"
  686.             print red("!!!")+" exception '%s' though." % str(e)
  687.             val=0
  688.         if not val:
  689.             print red("!!!")+" fetching new metadata.dtd failed, aborting"
  690.             sys.exit(1)
  691.     #this can be problematic if xmllint changes their output
  692.     xmllint_capable=True
  693.  
  694.  
  695. def x11_deprecation_check(depstr):
  696.     if depstr.find("virtual/x11") == -1:
  697.         return False
  698.     depsplit = depstr.split()
  699.     ok_stack = []
  700.     ok = False
  701.     for token in depsplit:
  702.         if token == "(":
  703.             ok_stack.append(ok)
  704.             ok = False
  705.         elif token == ")":
  706.             ok = ok_stack.pop()
  707.         elif token == "||":
  708.             ok = True
  709.         else:
  710.             ok = False
  711.             if token.find("virtual/x11") != -1 and (not ok_stack or not ok_stack[-1]):
  712.                 return True
  713.     return False
  714.  
  715.  
  716. arch_caches={}
  717. for x in scanlist:
  718.     #ebuilds and digests added to cvs respectively.
  719.     if verbose:
  720.         print "checking package " + x
  721.     eadded=[]
  722.     dadded=[]
  723.     cladded=0
  724.     catdir,pkgdir=x.split("/")
  725.     checkdir=repodir+"/"+x
  726.     checkdirlist=os.listdir(checkdir)
  727.     ebuildlist=[]
  728.     for y in checkdirlist:
  729.         if y[-7:]==".ebuild":
  730.             ebuildlist.append(y[:-7])
  731.         if y in ["Manifest","ChangeLog","metadata.xml"]:
  732.             if os.stat(checkdir+"/"+y)[0] & 0x0248:
  733.                 stats["file.executable"] += 1
  734.                 fails["file.executable"].append(checkdir+"/"+y)
  735.     digestlist=[]
  736.  
  737.     for y in checkdirlist:
  738.         for c in y.strip(os.path.sep):
  739.             if c not in allowed_filename_chars_set:
  740.                 stats["file.name"] += 1
  741.                 fails["file.name"].append("%s/%s: char '%s'" % (checkdir, y, c))
  742.                 break
  743.  
  744.         if not (y in ("ChangeLog", "metadata.xml") or y.endswith(".ebuild")):
  745.             continue
  746.         try:
  747.             line = 1
  748.             for l in codecs.open(checkdir+"/"+y, "r", "utf8"):
  749.                 line +=1
  750.         except UnicodeDecodeError, ue:
  751.             stats["file.UTF8"] += 1
  752.             s = ue.object[:ue.start]
  753.             l2 = s.count("\n")
  754.             line += l2
  755.             if l2 != 0:
  756.                 s = s[s.rfind("\n") + 1:]
  757.             fails["file.UTF8"].append("%s/%s: line %i, just after: '%s'" % (checkdir, y, line, s))
  758.  
  759.     if isCvs:
  760.         try:
  761.             mystat=os.stat(checkdir+"/files")[0]
  762.             if len(ebuildlist) and not S_ISDIR(mystat):
  763.                 raise Exception
  764.         except SystemExit, e:
  765.             raise  # Need to propogate this
  766.         except:
  767.             stats["filedir.missing"] += 1
  768.             fails["filedir.missing"].append(checkdir)
  769.             continue
  770.         try:
  771.             myf=open(checkdir+"/CVS/Entries","r")
  772.             myl=myf.readlines()
  773.             for l in myl:
  774.                 if l[0]!="/":
  775.                     continue
  776.                 splitl=l[1:].split("/")
  777.                 if not len(splitl):
  778.                     continue
  779.                 objsadded.append(splitl[0])
  780.                 if splitl[0][-7:]==".ebuild":
  781.                     eadded.append(splitl[0][:-7])
  782.                 if splitl[0]=="ChangeLog":
  783.                     cladded=1
  784.         except IOError:
  785.             if mymode=="commit":
  786.                 stats["CVS/Entries.IO_error"] += 1
  787.                 fails["CVS/Entries.IO_error"].append(checkdir+"/CVS/Entries")
  788.             continue
  789.  
  790.         try:
  791.             myf=open(checkdir+"/files/CVS/Entries","r")
  792.             myl=myf.readlines()
  793.             for l in myl:
  794.                 if l[0]!="/":
  795.                     continue
  796.                 splitl=l[1:].split("/")
  797.                 if not len(splitl):
  798.                     continue
  799.                 objsadded.append(splitl[0])
  800.                 if splitl[0][:7]=="digest-":
  801.                     dadded.append(splitl[0][7:])
  802.         except IOError:
  803.             if mymode=="commit":
  804.                 stats["CVS/Entries.IO_error"] += 1
  805.                 fails["CVS/Entries.IO_error"].append(checkdir+"/files/CVS/Entries")
  806.             continue
  807.  
  808.     if mymode == "commit":
  809.         repoman_settings["O"] = checkdir
  810.         portage.digestgen([], repoman_settings, manifestonly=1, myportdb=portage.portdb)
  811.  
  812.     mf = Manifest(checkdir, repoman_settings["DISTDIR"])
  813.     mydigests=mf.getTypeDigests("DIST")
  814.     myfiles_all = []
  815.  
  816.     if os.path.exists(checkdir+"/files"):
  817.         filesdirlist=os.listdir(checkdir+"/files")
  818.         for y in filesdirlist:
  819.             if y[:7]=="digest-":
  820.                 if y[7:] not in dadded:
  821.                     #digest not added to cvs
  822.                     stats["digest.notadded"]=stats["digest.notadded"]+1
  823.                     fails["digest.notadded"].append(x+"/files/"+y)
  824.                     if y[7:] in eadded:
  825.                         stats["digest.disjointed"]=stats["digest.disjointed"]+1
  826.                         fails["digest.disjointed"].append(x+"/files/"+y)
  827.                         
  828.                 if os.stat(checkdir+"/files/"+y)[0] & 0x0248:
  829.                     stats["file.executable"] += 1
  830.                     fails["file.executable"].append(x+"/files/"+y)
  831.                 
  832.                 mykey = catdir + "/" + y[7:]
  833.                 if y[7:] not in ebuildlist:
  834.                     #stray digest
  835.                     if mymode=="fix":
  836.                         if "--pretend" in myoptions:
  837.                             print "(cd "+repodir+"/"+x+"/files; cvs rm -f "+y+")"
  838.                         else:
  839.                             os.system("(cd "+repodir+"/"+x+"/files; cvs rm -f "+y+")")
  840.                     else:
  841.                         stats["digest.stray"]=stats["digest.stray"]+1
  842.                         fails["digest.stray"].append(x+"/files/"+y)
  843.                 else:
  844.                     # We have an ebuild
  845.                     myuris,myfiles = portage.db["/"]["porttree"].dbapi.getfetchlist(mykey,all=True)
  846.                     myfiles_all.extend(myfiles)
  847.  
  848.                     uri_dict = {}
  849.                     for myu in myuris:
  850.                         myubn = os.path.basename(myu)
  851.                         if myubn not in uri_dict:
  852.                             uri_dict[myubn]  = [myu]
  853.                         else:
  854.                             uri_dict[myubn] += [myu]
  855.  
  856.                     for myf in uri_dict:
  857.                         myff = repoman_settings["DISTDIR"] + "/" + myf
  858.                         if not mydigests.has_key(myf):
  859.                             uri_settings = portage.config(clone=repoman_settings)
  860.                             if mymode == "fix":
  861.                                 if not portage.fetch(uri_dict[myf], uri_settings):
  862.                                     stats["digest.unmatch"] += 1
  863.                                     fails["digest.unmatch"].append(y+"::"+myf)
  864.                                 else:
  865.                                     eb_name,eb_location = portage.db["/"]["porttree"].dbapi.findname2(mykey)
  866.                                     portage.doebuild(eb_name, "digest", "/", uri_settings, tree="porttree")
  867.                             else:
  868.                                 stats["digest.partial"] += 1
  869.                                 fails["digest.partial"].append(y+"::"+myf)
  870.                         elif "assume-digests" not in repoman_settings.features:
  871.                             if os.path.exists(myff):
  872.                                 if not portage_checksum.verify_all(myff, mydigests[myf]):
  873.                                     stats["digest.fail"] += 1
  874.                                     fails["digest.fail"].append(y+"::"+myf)
  875.                             elif repolevel == 3:
  876.                                 stats["digest.assumed"] += 1
  877.                                 fails["digest.assumed"].append(y+"::"+myf)
  878.  
  879.         # recurse through files directory
  880.         # use filesdirlist as a stack, appending directories as needed so people can't hide > 20k files in a subdirectory.
  881.         while filesdirlist:
  882.             y = filesdirlist.pop(0)
  883.             try:
  884.                 mystat = os.stat(checkdir+"/files/"+y)
  885.             except OSError, oe:
  886.                 if oe.errno == 2:
  887.                     # don't worry about it.  it likely was removed via fix above.
  888.                     continue
  889.                 else:
  890.                     raise oe
  891.             if S_ISDIR(mystat.st_mode):
  892.                 if y == "CVS":
  893.                     continue
  894.                 for z in os.listdir(checkdir+"/files/"+y):
  895.                     if z == "CVS":
  896.                         continue
  897.                     filesdirlist.append(y+"/"+z)
  898.             # current policy is no files over 20k, this is the check.
  899.             elif mystat.st_size > 20480:
  900.                 stats["file.size"] += 1
  901.                 fails["file.size"].append("("+ str(mystat.st_size/1024) + "K) "+x+"/files/"+y)
  902.  
  903.             for c in os.path.basename(y.rstrip(os.path.sep)):
  904.                 if c not in allowed_filename_chars_set:
  905.                     stats["file.name"] += 1
  906.                     fails["file.name"].append("%s/files/%s: char '%s'" % (checkdir, y, c))
  907.                     break
  908.  
  909.     for entry in mydigests.keys():
  910.         if entry not in myfiles_all:
  911.             stats["digestentry.unused"] += 1
  912.             fails["digestentry.unused"].append(checkdir+"::"+entry)
  913.  
  914.  
  915.     if "ChangeLog" not in checkdirlist:
  916.         stats["changelog.missing"]+=1
  917.         fails["changelog.missing"].append(x+"/ChangeLog")
  918.     
  919.     #metadata.xml file check
  920.     if "metadata.xml" not in checkdirlist:
  921.         stats["metadata.missing"]+=1
  922.         fails["metadata.missing"].append(x+"/metadata.xml")
  923.     #metadata.xml parse check
  924.     else:
  925.         #Only carry out if in package directory or check forced
  926.         if xmllint_capable:
  927.             st=getstatusoutput("xmllint --nonet --noout --dtdvalid %s/metadata.dtd %s/metadata.xml" % (portage.CACHE_PATH, checkdir))
  928.             if st[0] != 0:
  929.                 for z in st[1].split("\n"):
  930.                     print red("!!! ")+z
  931.                 stats["metadata.bad"]+=1
  932.                 fails["metadata.bad"].append(x+"/metadata.xml")
  933.  
  934.     allmasked = True
  935.  
  936.     for y in ebuildlist:
  937.         if os.stat(checkdir+"/"+y+".ebuild")[0] & 0x0248:
  938.             stats["file.executable"] += 1
  939.             fails["file.executable"].append(x+"/"+y+".ebuild")
  940.         if y not in eadded:
  941.             #ebuild not added to cvs
  942.             stats["ebuild.notadded"]=stats["ebuild.notadded"]+1
  943.             fails["ebuild.notadded"].append(x+"/"+y+".ebuild")
  944.             if y in dadded:
  945.                 stats["ebuild.disjointed"]=stats["ebuild.disjointed"]+1
  946.                 fails["ebuild.disjointed"].append(x+"/"+y+".ebuild")
  947.         if not os.path.exists(checkdir+"/files/digest-"+y):
  948.             if mymode=="fix":
  949.                 if "--pretend" in myoptions:
  950.                     print "You will need to run:"
  951.                     print "  /usr/bin/ebuild "+repodir+"/"+x+"/"+y+".ebuild digest"
  952.                 else:
  953.                     retval=os.system("/usr/bin/ebuild "+repodir+"/"+x+"/"+y+".ebuild digest")
  954.                     if retval:
  955.                         print "!!! Exiting on ebuild digest (shell) error code:",retval
  956.                         sys.exit(retval)
  957.             else:
  958.                 stats["digest.missing"]=stats["digest.missing"]+1
  959.                 fails["digest.missing"].append(x+"/files/digest-"+y)
  960.         myesplit=portage.pkgsplit(y)
  961.         if myesplit is None or not valid_ebuild_name(x.split("/")[0]+"/"+y):
  962.             stats["ebuild.invalidname"]=stats["ebuild.invalidname"]+1
  963.             fails["ebuild.invalidname"].append(x+"/"+y+".ebuild")
  964.             continue
  965.         elif myesplit[0]!=pkgdir:
  966.             print pkgdir,myesplit[0]
  967.             stats["ebuild.namenomatch"]=stats["ebuild.namenomatch"]+1
  968.             fails["ebuild.namenomatch"].append(x+"/"+y+".ebuild")
  969.             continue
  970.         try:
  971.             myaux = dict( zip(allvars, portage.db["/"]["porttree"].dbapi.aux_get(catdir+"/"+y, allvars ) ) )
  972.         except KeyError:
  973.             stats["ebuild.syntax"]=stats["ebuild.syntax"]+1
  974.             fails["ebuild.syntax"].append(x+"/"+y+".ebuild")
  975.             continue
  976.         except IOError:
  977.             stats["ebuild.output"]=stats["ebuild.output"]+1
  978.             fails["ebuild.output"].append(x+"/"+y+".ebuild")
  979.             continue
  980.  
  981.         # Test for negative logic and bad words in the RESTRICT var.
  982.         #for x in myaux[allvars.index("RESTRICT")].split():
  983.         #    if x.startswith("no"):
  984.         #        print "Bad RESTRICT value: %s" % x
  985.  
  986.         myaux["PROVIDE"] = portage_dep.use_reduce(portage_dep.paren_reduce(myaux["PROVIDE"]), matchall=1)
  987.         myaux["PROVIDE"] = " ".join(portage.flatten(myaux["PROVIDE"]))
  988.         for myprovide in myaux["PROVIDE"].split():
  989.             prov_cp = portage.dep_getkey(myprovide)
  990.             if prov_cp != myprovide:
  991.                 stats["virtual.versioned"]+=1
  992.                 fails["virtual.versioned"].append(x+"/"+y+".ebuild: "+myprovide)
  993.             prov_pkg = portage.dep_getkey(portage.best(portage.db["/"]["porttree"].dbapi.xmatch("match-all", prov_cp)))
  994.             if prov_cp == prov_pkg:
  995.                 stats["virtual.exists"]+=1
  996.                 fails["virtual.exists"].append(x+"/"+y+".ebuild: "+prov_cp)
  997.  
  998.         for pos in range(0,len(missingvars)):
  999.             if not myaux[missingvars[pos]]:
  1000.                 myqakey=missingvars[pos]+".missing"
  1001.                 stats[myqakey]=stats[myqakey]+1
  1002.                 fails[myqakey].append(x+"/"+y+".ebuild")
  1003.  
  1004.         # KEYWORDS="-*" is a stupid replacement for package.mask and screws general KEYWORDS semantics
  1005.         if "-*" in myaux["KEYWORDS"].split():
  1006.             haskeyword = False
  1007.             for kw in myaux["KEYWORDS"].split():
  1008.                 if kw[0] == "~":
  1009.                     kw = kw[1:]
  1010.                 if kw in kwlist:
  1011.                     haskeyword = True
  1012.             if not haskeyword:
  1013.                 stats["KEYWORDS.stupid"] += 1
  1014.                 fails["KEYWORDS.stupid"].append(x+"/"+y+".ebuild")
  1015.  
  1016.         """
  1017.         Ebuilds that inherit a "Live" eclasss (darcs,subversion,git,cvs,etc..) should
  1018.         not be allowed to be marked stable
  1019.         """
  1020.         if set(["darcs","cvs","subversion","git"]).intersection(myaux["INHERITED"].split()):
  1021.             bad_stable_keywords = [keyword for keyword in myaux["KEYWORDS"].split() if not keyword.startswith("~") and not keyword.startswith("-")]
  1022.             if bad_stable_keywords:
  1023.                 stats["LIVEVCS.stable"] += 1
  1024.                 fails["LIVEVCS.stable"].append(x+"/"+y+".ebuild with stable keywords:%s " % bad_stable_keywords)
  1025.             del keyword, bad_stable_keywords        
  1026.  
  1027.         if "--ignore-arches" in myoptions:
  1028.             arches = [[repoman_settings["ARCH"], repoman_settings["ARCH"],
  1029.                 repoman_settings["ACCEPT_KEYWORDS"].split()]]
  1030.         else:
  1031.             arches=[]
  1032.             for keyword in myaux["KEYWORDS"].split():
  1033.                 if (keyword[0]=="-"):
  1034.                     continue
  1035.                 elif (keyword[0]=="~"):
  1036.                     arches.append([keyword, keyword[1:], [keyword[1:], keyword]])
  1037.                 else:
  1038.                     arches.append([keyword, keyword, [keyword]])
  1039.                     allmasked = False
  1040.  
  1041.         baddepsyntax = False
  1042.         badlicsyntax = False
  1043.         badprovsyntax = False
  1044.         catpkg = catdir+"/"+y
  1045.         myiuse = myaux["IUSE"].split() + repoman_settings.archlist()
  1046.         type_list, badsyntax = [], []
  1047.         for mytype in ("DEPEND", "RDEPEND", "PDEPEND", "LICENSE", "PROVIDE"):
  1048.             mydepstr = myaux[mytype]
  1049.             
  1050.             if (string.find(mydepstr, " ?") != -1):
  1051.                 badsyntax.append("'?' preceded by space")
  1052.  
  1053.             try:
  1054.                 # Missing closing parenthesis will result in a ValueError
  1055.                 mydeplist = portage_dep.paren_reduce(mydepstr)
  1056.                 # Missing opening parenthesis will result in a final "" element
  1057.                 if "" in mydeplist or "(" in mydeplist:
  1058.                     raise ValueError
  1059.             except ValueError:
  1060.                 badsyntax.append("parenthesis mismatch")
  1061.                 mydeplist = []
  1062.  
  1063.             try:
  1064.                 portage_dep.use_reduce(mydeplist, excludeall=myiuse)
  1065.             except portage_exception.InvalidDependString, e:
  1066.                 badsyntax.append(str(e))
  1067.  
  1068.             for token in ("||", "(", ")"):
  1069.                 if mydepstr.startswith(token+" "):
  1070.                     myteststr = mydepstr[len(token):]
  1071.                 else:
  1072.                     myteststr = mydepstr
  1073.                 if myteststr.endswith(" "+token):
  1074.                     myteststr = myteststr[:-len(token)]
  1075.                 while myteststr.find(" "+token+" ") != -1:
  1076.                     myteststr = " ".join(myteststr.split(" "+token+" ", 1))
  1077.                 if myteststr.find(token) != -1:
  1078.                     badsyntax.append("'%s' not separated by space" % (token))
  1079.  
  1080.  
  1081.             if mytype in ("DEPEND", "RDEPEND", "PDEPEND"):
  1082.                 for token in filter(lambda x: not (x.endswith("?") or x.strip() in ("||", "&&", "(", ")")), mydepstr.split()):
  1083.                     if not "/" in token:
  1084.                         badsyntax.append("'%s' not a valid atom" % token)
  1085.  
  1086.             type_list.extend([mytype] * (len(badsyntax) - len(type_list)))
  1087.  
  1088.         for m,b in zip(type_list, badsyntax):
  1089.             stats[m+".syntax"] += 1
  1090.             fails[m+".syntax"].append(catpkg+".ebuild "+m+": "+b)
  1091.  
  1092.         badlicsyntax = len(filter(lambda x:x=="LICENSE", type_list))
  1093.         badprovsyntax = len(filter(lambda x:x=="PROVIDE", type_list))
  1094.         baddepsyntax = len(type_list) != badlicsyntax + badprovsyntax 
  1095.         badlicsyntax = badlicsyntax > 0
  1096.         badprovsyntax = badprovsyntax > 0
  1097.  
  1098.         if not baddepsyntax:
  1099.             if x11_deprecation_check(" ".join([myaux["DEPEND"], myaux["RDEPEND"], myaux["PDEPEND"]])):
  1100.                 stats["usage.obsolete"] += 1
  1101.                 fails["usage.obsolete"].append("%s/%s.ebuild: not migrated to modular X" % (x, y))
  1102.  
  1103.         for keyword,arch,groups in arches:
  1104.  
  1105.             if not profiles.has_key(arch):
  1106.                 # A missing profile will create an error further down
  1107.                 # during the KEYWORDS verification.
  1108.                 continue
  1109.                 
  1110.             for prof in profiles[arch]:
  1111.  
  1112.                 profdir = portdir+"/profiles/"+prof[0]
  1113.     
  1114.                 if arch_caches.has_key(prof[0]):
  1115.                     dep_settings, portage.portdb, portage.db["/"]["porttree"] = arch_caches[prof[0]]
  1116.                 else:
  1117.                     dep_settings=portage.config(config_profile_path=profdir, config_incrementals=portage_const.INCREMENTALS)
  1118.                     portage.portdb=portage.portdbapi(portdir, dep_settings)
  1119.                     portage.db["/"]["porttree"]=portage.portagetree("/",dep_settings.getvirtuals("/"))
  1120.                     arch_caches[prof[0]]=[dep_settings, portage.portdb, portage.db["/"]["porttree"]]
  1121.  
  1122.                 dep_settings["ACCEPT_KEYWORDS"] = " ".join(groups)
  1123.  
  1124.                 for myprovide in myaux["PROVIDE"].split():
  1125.                     prov_cp = portage.dep_getkey(myprovide)
  1126.                     if prov_cp not in dep_settings.getvirtuals():
  1127.                         stats["virtual.unavailable"]+=1
  1128.                         fails["virtual.unavailable"].append(x+"/"+y+".ebuild: "+keyword+"("+prof[0]+") "+prov_cp)
  1129.  
  1130.                 if not baddepsyntax:
  1131.                     ismasked = (catdir+"/"+y not in portage.db["/"]["porttree"].dbapi.xmatch("list-visible",x))
  1132.                     if ismasked:
  1133.                         if "--ignore-masked" in myoptions:
  1134.                             continue
  1135.                         #we are testing deps for a masked package; give it some lee-way
  1136.                         suffix="masked"
  1137.                         matchmode="match-all"
  1138.                     else:
  1139.                         suffix=""
  1140.                         matchmode="match-visible"
  1141.     
  1142.                     if prof[1] == "dev":
  1143.                         suffix=suffix+"indev"
  1144.                     
  1145.                     for mytype,mypos in [["DEPEND",len(missingvars)],["RDEPEND",len(missingvars)+1],["PDEPEND",len(missingvars)+2]]:
  1146.                         
  1147.                         mykey=mytype+".bad"+suffix
  1148.                         myvalue = myaux[mytype]
  1149.                         if not myvalue:
  1150.                             continue
  1151.                         try:
  1152.                             mydep=portage.dep_check(myvalue,portage.db["/"]["porttree"].dbapi,dep_settings,use="all",mode=matchmode)
  1153.                         except KeyError, e:
  1154.                             stats[mykey]=stats[mykey]+1
  1155.                             fails[mykey].append(x+"/"+y+".ebuild: "+keyword+"("+prof[0]+") "+repr(e[0]))
  1156.                             continue
  1157.     
  1158.                         if mydep[0]==1:
  1159.                             if mydep[1]!=[]:
  1160.                                 #we have some unsolvable deps
  1161.                                 #remove ! deps, which always show up as unsatisfiable
  1162.                                 d=0
  1163.                                 while d<len(mydep[1]):
  1164.                                     if mydep[1][d][0]=="!":
  1165.                                         del mydep[1][d]
  1166.                                     else:
  1167.                                         d += 1
  1168.                                 #if we emptied out our list, continue:
  1169.                                 if not mydep[1]:
  1170.                                     continue
  1171.                                 stats[mykey]=stats[mykey]+1
  1172.                                 fails[mykey].append(x+"/"+y+".ebuild: "+keyword+"("+prof[0]+") "+repr(mydep[1]))
  1173.                         else:
  1174.                             stats[mykey]=stats[mykey]+1
  1175.                             fails[mykey].append(x+"/"+y+".ebuild: "+keyword+"("+prof[0]+") "+repr(mydep[1]))
  1176.  
  1177.         # this check needs work, it won't catch (\ndie)
  1178.         if not os.system("egrep '^[^#]*\([^)]*\<die\>' "+checkdir+"/"+y+".ebuild >/dev/null 2>&1"):
  1179.             stats["ebuild.nesteddie"]=stats["ebuild.nesteddie"]+1
  1180.             fails["ebuild.nesteddie"].append(x+"/"+y+".ebuild")
  1181.         # uselist checks - global
  1182.         myuse = myaux["IUSE"].split()
  1183.         for mypos in range(len(myuse)-1,-1,-1):
  1184.             if myuse[mypos] and (myuse[mypos] in uselist):
  1185.                 del myuse[mypos]
  1186.         # uselist checks - local
  1187.         mykey = portage.dep_getkey(catpkg)
  1188.         if luselist.has_key(mykey):
  1189.             for mypos in range(len(myuse)-1,-1,-1):
  1190.                 if myuse[mypos] and (myuse[mypos] in luselist[mykey]):
  1191.                     del myuse[mypos]
  1192.         for mypos in range(len(myuse)):
  1193.             stats["IUSE.invalid"]=stats["IUSE.invalid"]+1
  1194.             fails["IUSE.invalid"].append(x+"/"+y+".ebuild: %s" % myuse[mypos])    
  1195.  
  1196.         # license checks
  1197.         if not badlicsyntax:
  1198.             myuse = myaux["LICENSE"]
  1199.             # Parse the LICENSE variable, remove USE conditions and
  1200.             # flatten it.
  1201.             myuse=portage_dep.use_reduce(portage_dep.paren_reduce(myuse), matchall=1)
  1202.             myuse=portage.flatten(myuse)
  1203.             # Check each entry to ensure that it exists in PORTDIR's
  1204.             # license directory.
  1205.             for mypos in range(0,len(myuse)):
  1206.                 # Need to check for "||" manually as no portage
  1207.                 # function will remove it without removing values.
  1208.                 if myuse[mypos] not in liclist and myuse[mypos] != "||":
  1209.                     stats["LICENSE.invalid"]=stats["LICENSE.invalid"]+1
  1210.                     fails["LICENSE.invalid"].append(x+"/"+y+".ebuild: %s" % myuse[mypos])
  1211.  
  1212.         #keyword checks
  1213.         myuse = myaux["KEYWORDS"].split()
  1214.         for mykey in myuse:
  1215.             myskey=mykey[:]
  1216.             if myskey[0]=="-":
  1217.                 myskey=myskey[1:]
  1218.             if myskey[0]=="~":
  1219.                 myskey=myskey[1:]
  1220.             if mykey!="-*":
  1221.                 if myskey not in kwlist:
  1222.                     stats["KEYWORDS.invalid"] += 1
  1223.                     fails["KEYWORDS.invalid"].append(x+"/"+y+".ebuild: %s" % mykey)
  1224.                 elif not profiles.has_key(myskey):
  1225.                     stats["KEYWORDS.invalid"] += 1
  1226.                     fails["KEYWORDS.invalid"].append(x+"/"+y+".ebuild: %s (profile invalid)" % mykey)
  1227.  
  1228.         #syntax checks
  1229.         myear = time.gmtime(os.stat(checkdir+"/"+y+".ebuild")[ST_MTIME])[0]
  1230.         gentoo_copyright = re.compile(r'^# Copyright ((1999|200\d)-)?' + str(myear) + r' Gentoo Foundation')
  1231.         gentoo_license = re.compile(r'^# Distributed under the terms of the GNU General Public License v2$')
  1232.         cvs_header = re.compile(r'^#\s*\$Header.*\$$')
  1233.         ignore_line = re.compile(r'(^$)|(^(\t)*#)')
  1234.         leading_spaces = re.compile(r'^[\S\t]')
  1235.         trailing_whitespace = re.compile(r'.*([\S]$)')
  1236.         readonly_assignment = re.compile(r'^\s*(export\s+)?(A|P|PV|PN|PR|PVR|PF|D|WORKDIR|FILESDIR|FEATURES|USE)=')
  1237.         continuation_symbol = re.compile(r'(.*[ ]+[\\][ ].*)')
  1238.         line_continuation_quoted = re.compile(r'(\"|\')(([\w ,:;#\[\]\.`=/|\$\^\*{}()\'-])|(\\.))*\1')
  1239.         line_continuation = re.compile(r'([^#]*\S)(\s+|\t)\\$')
  1240.         linenum=0
  1241.         previous_line = None
  1242.         for line in input(checkdir+"/"+y+".ebuild"):
  1243.             linenum += 1
  1244.             # Gentoo copyright check
  1245.             if linenum == 1:
  1246.                 match = gentoo_copyright.match(line)
  1247.                 if not match:
  1248.                     myerrormsg = "Copyright header Error. Possibly date related."
  1249.                     stats["ebuild.badheader"] +=1
  1250.                     fails["ebuild.badheader"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
  1251.             # Gentoo license check
  1252.             elif linenum == 2:
  1253.                 match = gentoo_license.match(line)
  1254.                 if not match:
  1255.                     myerrormsg = "Gentoo License Error."
  1256.                     stats["ebuild.badheader"] +=1
  1257.                     fails["ebuild.badheader"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
  1258.             # CVS Header check
  1259.             elif linenum == 3:
  1260.                 match = cvs_header.match(line)
  1261.                 if not match:
  1262.                     myerrormsg = "CVS Header Error."
  1263.                     stats["ebuild.badheader"] +=1
  1264.                     fails["ebuild.badheader"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
  1265.             else:
  1266.                 match = ignore_line.match(line)
  1267.                 if not match:
  1268.                     # Excluded Blank lines and full line comments. Good!
  1269.                     # Leading Spaces Check
  1270.                     match = leading_spaces.match(line)
  1271.                     if not match:
  1272.                         #Line has got leading spaces. Bad!
  1273.                         myerrormsg = "Leading Space Syntax Error. Line %d" % linenum
  1274.                         stats["ebuild.minorsyn"] +=1
  1275.                         fails["ebuild.minorsyn"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
  1276.                     # Trailing whitespace check
  1277.                     match = trailing_whitespace.match(line)
  1278.                     if not match:
  1279.                         #Line has got trailing whitespace. Bad!
  1280.                         myerrormsg = "Trailing whitespace Syntax Error. Line %d" % linenum
  1281.                         stats["ebuild.minorsyn"] +=1
  1282.                         fails["ebuild.minorsyn"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
  1283.                     # Readonly variable assignment check
  1284.                     match = readonly_assignment.match(line)
  1285.                     # The regex can give a false positive for continued lines,
  1286.                     # so we check the previous line to see if it was continued.
  1287.                     if match and (not previous_line or not line_continuation.match(previous_line)):
  1288.                         # invalid assignment, very bad!
  1289.                         myerrormsg = "Readonly variable assignment to %s on line %d" % (match.group(2), linenum)
  1290.                         stats["variable.readonly"] += 1
  1291.                         fails["variable.readonly"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
  1292.                     # Line continuation check
  1293.                     match = continuation_symbol.match(line)
  1294.                     if match:
  1295.                         #Excluded lines not even containing a " \" match. Good!
  1296.                         line = re.sub(line_continuation_quoted,"\"\"",line)
  1297.                         #line has been edited to collapsed "" and '' quotes to "". Good!
  1298.                         match = continuation_symbol.match(line)
  1299.                         if match:
  1300.                             #Again exclude lines not even containing a " \" match. Good!
  1301.                             #This repetition is done for a slight performance increase
  1302.                             match = line_continuation.match(line)
  1303.                             if not match:
  1304.                                 #Line has a line continuation error. Bad!
  1305.                                 myerrormsg = "Line continuation (\"\\\") Syntax Error. Line %d" % linenum
  1306.                                 stats["ebuild.majorsyn"] +=1
  1307.                                 fails["ebuild.majorsyn"].append(x+"/"+y+".ebuild: %s" % myerrormsg)
  1308.             previous_line = line
  1309.         del previous_line
  1310.  
  1311.     # Check for 'all unstable' or 'all masked' -- ACCEPT_KEYWORDS is stripped
  1312.     # XXX -- Needs to be implemented in dep code. Can't determine ~arch nicely.
  1313.     #if not portage.portdb.xmatch("bestmatch-visible",x):
  1314.     #    stats["ebuild.nostable"]+=1
  1315.     #    fails["ebuild.nostable"].append(x)
  1316.     if allmasked and repolevel == 3:
  1317.         stats["ebuild.allmasked"]+=1
  1318.         fails["ebuild.allmasked"].append(x)
  1319.  
  1320. #Pickle and save results for instant reuse in last and lfull
  1321. savef=open('/var/cache/edb/repo.stats','w')
  1322. pickle.dump(stats,savef)
  1323. savef.close()
  1324. savef=open('/var/cache/edb/repo.fails','w')
  1325. pickle.dump(fails,savef)
  1326. savef.close()
  1327. if not (os.stat('/var/cache/edb/repo.stats')[ST_GID] == getgrnam('portage')[2]):
  1328.     os.chown('/var/cache/edb/repo.stats',os.geteuid(),getgrnam('portage')[2])
  1329.     os.chmod('/var/cache/edb/repo.stats',0664)
  1330. if not (os.stat('/var/cache/edb/repo.fails')[ST_GID] == getgrnam('portage')[2]):
  1331.     os.chown('/var/cache/edb/repo.fails',os.geteuid(),getgrnam('portage')[2])
  1332.     os.chmod('/var/cache/edb/repo.fails',0664)
  1333. if quiet < 2:
  1334.     print
  1335. #dofail will be set to 1 if we have failed in at least one non-warning category
  1336. dofail=0
  1337. #dowarn will be set to 1 if we tripped any warnings
  1338. dowarn=0
  1339. #dofull will be set if we should print a "repoman full" informational message
  1340. dofull=0
  1341. for x in qacats:
  1342.     if not isCvs and (string.find(x, "notadded") != -1):
  1343.         stats[x] = 0
  1344.     if stats[x]:
  1345.         dowarn=1
  1346.         if x not in qawarnings:
  1347.             dofail=1
  1348.     else:
  1349.         continue
  1350.     print "  "+string.ljust(x,30),
  1351.     if stats[x]==0:
  1352.         print green(`stats[x]`)
  1353.         continue
  1354.     elif x in qawarnings:
  1355.         print yellow(`stats[x]`)
  1356.     else:
  1357.         print red(`stats[x]`)
  1358.     if mymode!="full":
  1359.         if stats[x]<12:
  1360.             for y in fails[x]:
  1361.                 print "   "+y
  1362.         else:
  1363.             dofull=1
  1364.     else:
  1365.         for y in fails[x]:
  1366.             print "   "+y
  1367.  
  1368. def grouplist(mylist,seperator="/"):
  1369.     """(list,seperator="/") -- Takes a list of elements; groups them into
  1370.     same initial element categories. Returns a dict of {base:[sublist]}
  1371.     From: ["blah/foo","spork/spatula","blah/weee/splat"]
  1372.     To:   {"blah":["foo","weee/splat"], "spork":["spatula"]}"""
  1373.     mygroups={}
  1374.     for x in mylist:
  1375.         xs=string.split(x,seperator)
  1376.         if xs[0]==".":
  1377.             xs=xs[1:]
  1378.         if xs[0] not in mygroups.keys():
  1379.             mygroups[xs[0]]=[string.join(xs[1:],seperator)]
  1380.         else:
  1381.             mygroups[xs[0]]+=[string.join(xs[1:],seperator)]
  1382.     return mygroups
  1383.  
  1384. if mymode!="commit":
  1385.     if dofull:
  1386.         print bold("Note: type \"repoman full\" for a complete listing.")
  1387.         if quiet < 1:
  1388.             print
  1389.     if dowarn and not dofail:
  1390.         if quiet < 2:
  1391.             print green("RepoMan sez:"),"\"You're only giving me a partial QA payment?\n              I'll take it this time, but I'm not happy.\""
  1392.         else:
  1393.             print green("RepoMan sez:"),"\"OK for now, but I'll be back ...\""
  1394.     elif not dofail:
  1395.         print green("RepoMan sez:"),"\"If everyone were like you, I'd be out of business!\""
  1396.     if quiet < 1:
  1397.         print
  1398. else:
  1399.     if dofail:
  1400.         print turquoise("Please fix these important QA issues first.")
  1401.         print green("RepoMan sez:"),"\"Make your QA payment on time and you'll never see the likes of me.\"\n"
  1402.         sys.exit(1)
  1403.  
  1404.     if "--pretend" in myoptions:
  1405.         print green("RepoMan sez:"), "\"So, you want to play it safe. Good call.\"\n"
  1406.  
  1407.     if fails["digest.missing"]:
  1408.         print green("Creating missing digests...")
  1409.     for x in fails["digest.missing"]:
  1410.         xs=string.split(x,"/")
  1411.         del xs[-2]
  1412.         myeb=string.join(xs[:-1],"/")+"/"+xs[-1][7:]
  1413.         if "--pretend" in myoptions:
  1414.             print "(ebuild "+portdir+"/"+myeb+".ebuild digest)"
  1415.         else:
  1416.             retval=os.system("ebuild "+portdir+"/"+myeb+".ebuild digest")
  1417.             if retval:
  1418.                 print "!!! Exiting on ebuild digest (shell) error code:",retval
  1419.                 sys.exit(retval)
  1420.  
  1421.     mycvstree=cvstree.getentries("./",recursive=1)
  1422.     if isCvs and not mycvstree:
  1423.         print "!!! It seems we don't have a cvs tree?"
  1424.         sys.exit(3)
  1425.  
  1426.     myunadded=cvstree.findunadded(mycvstree,recursive=1,basedir="./")
  1427.     myautoadd=[]
  1428.     if myunadded:
  1429.         for x in range(len(myunadded)-1,-1,-1):
  1430.             xs=string.split(myunadded[x],"/")
  1431.             if xs[-1]=="files":
  1432.                 print "!!! files dir is not added! Please correct this."
  1433.                 sys.exit(-1)
  1434.             elif xs[-1]=="Manifest":
  1435.                 # It's a manifest... auto add
  1436.                 myautoadd+=[myunadded[x]]
  1437.                 del myunadded[x]
  1438.             elif len(xs[-1])>=7:
  1439.                 if xs[-1][:7]=="digest-":
  1440.                     del xs[-2]
  1441.                     myeb=string.join(xs[:-1]+[xs[-1][7:]],"/")+".ebuild"
  1442.                     if os.path.exists(myeb):
  1443.                         # Ebuild exists for digest... So autoadd it.
  1444.                         myautoadd+=[myunadded[x]]
  1445.                         del myunadded[x]
  1446.         
  1447.     if myautoadd:
  1448.         print ">>> Auto-Adding missing digests..."
  1449.         if "--pretend" in myoptions:
  1450.             print "(/usr/bin/cvs add "+string.join(myautoadd)+")"
  1451.             retval=0
  1452.         else:
  1453.             retval=os.system("/usr/bin/cvs add "+string.join(myautoadd))
  1454.         if retval:
  1455.             print "!!! Exiting on cvs (shell) error code:",retval
  1456.             sys.exit(retval)
  1457.  
  1458.     if myunadded:
  1459.         print red("!!! The following files are in your cvs tree but are not added to the master")
  1460.         print red("!!! tree. Please remove them from the cvs tree or add them to the master tree.")
  1461.         for x in myunadded:
  1462.             print "   ",x
  1463.         print
  1464.         print
  1465.         sys.exit(1)
  1466.  
  1467.     mymissing=None
  1468.     if mymissing:
  1469.         print "The following files are obviously missing from your cvs tree"
  1470.         print "and are being fetched so we can continue:"
  1471.         for x in mymissing:
  1472.             print "   ",x
  1473.         if "--pretend" in myoptions:
  1474.             print "(/usr/bin/cvs -q up "+string.join(mymissing)+")"
  1475.             retval=0
  1476.         else:
  1477.             retval=os.system("/usr/bin/cvs -q up "+string.join(mymissing))
  1478.         if retval:
  1479.             print "!!! Exiting on cvs (shell) error code:",retval
  1480.             sys.exit(retval)
  1481.         del mymissing
  1482.  
  1483.     retval=["",""]
  1484.     if isCvs:
  1485.         print "Performing a "+green("cvs -n up")+" with a little magic grep to check for updates."
  1486.         retval=getstatusoutput("/usr/bin/cvs -n up 2>&1 | egrep '^[^\?] .*' | egrep -v '^. .*/digest-[^/]+|^cvs server: .* -- ignored$'")
  1487.         
  1488.     mylines=string.split(retval[1], "\n")
  1489.     myupdates=[]
  1490.     for x in mylines:
  1491.         if not x:
  1492.             continue
  1493.         if x[0] not in "UPMAR": # Updates,Patches,Modified,Added,Removed
  1494.             print red("!!! Please fix the following issues reported from cvs: ")+green("(U,P,M,A,R are ok)")
  1495.             print red("!!! Note: This is a pretend/no-modify pass...")
  1496.             print retval[1]
  1497.             print
  1498.             sys.exit(1)
  1499.         elif x[0] in ["U","P"]:
  1500.             myupdates+=[x[2:]]
  1501.     
  1502.     if myupdates:
  1503.         print green("Fetching trivial updates...")
  1504.         if "--pretend" in myoptions:
  1505.             print "(/usr/bin/cvs up "+string.join(myupdates)+")"
  1506.             retval=0
  1507.         else:
  1508.             retval=os.system("/usr/bin/cvs up "+string.join(myupdates))
  1509.         if retval!=0:
  1510.             print "!!! cvs exited with an error. Terminating."
  1511.             sys.exit(retval)
  1512.     
  1513.     if isCvs:
  1514.         mycvstree=cvstree.getentries("./",recursive=1)
  1515.         mychanged=cvstree.findchanged(mycvstree,recursive=1,basedir="./")
  1516.         for manifest in [file for file in mychanged if '/Manifest' in file]:
  1517.             mychanged.remove(manifest)
  1518.         mynew=cvstree.findnew(mycvstree,recursive=1,basedir="./")
  1519.         myremoved=cvstree.findremoved(mycvstree,recursive=1,basedir="./")
  1520.         if not (mychanged or mynew or myremoved):
  1521.             print
  1522.             print green("RepoMan sez:"), "\"Doing nothing is not always good for QA.\"\n"
  1523.             print
  1524.             print "(Didn't find any changed files...)"
  1525.             print
  1526.             sys.exit(0)
  1527.  
  1528.     myupdates=mychanged+mynew
  1529.     myheaders=[]
  1530.     mydirty=[]
  1531.     headerstring="'\$(Header|Id)"
  1532.     headerstring+=".*\$'"
  1533.     for myfile in myupdates:
  1534.         myout=getstatusoutput("egrep -q "+headerstring+" "+myfile)
  1535.         if myout[0]==0:
  1536.             myheaders.append(myfile)
  1537.  
  1538.     print "*",green(str(len(myupdates))),"files being committed...",green(str(len(myheaders))),"have headers that will change."
  1539.     print "*","Files with headers will cause the manifests to be made and recommited."
  1540.     if quiet == 0:
  1541.         print "myupdates:",myupdates
  1542.         print "myheaders:",myheaders
  1543.         print
  1544.     unlinkfile=0
  1545.     if commitmessagefile:
  1546.         try:
  1547.             f = open(commitmessagefile)
  1548.             commitmessage = f.read()
  1549.             f.close()
  1550.             del f
  1551.         except (IOError, OSError), e:
  1552.             if e.errno == errno.ENOENT:
  1553.                 portage.writemsg("!!! File Not Found: --commitmsgfile='%s'\n" % commitmessagefile)
  1554.             else:
  1555.                 raise
  1556.         # We've read the content so the file is no longer needed.
  1557.         commitmessagefile = None
  1558.     if not commitmessage:
  1559.         print "Please enter a CVS commit message at the prompt:"
  1560.         while not commitmessage:
  1561.             try:
  1562.                 commitmessage=raw_input(green("> "))
  1563.             except KeyboardInterrupt: 
  1564.                 exithandler()
  1565.     try:
  1566.         commitmessage+="\n(Portage version: "+str(portage.VERSION)+")"
  1567.     except AttributeError:
  1568.         print "Failed to insert portage version in message!"
  1569.         commitmessage+="\n(Portage version: Unknown)"
  1570.     if not commitmessagefile:
  1571.         unlinkfile=1
  1572.         commitmessagefile=tempfile.mktemp(".repoman.msg")
  1573.         if os.path.exists(commitmessagefile):
  1574.             os.unlink(commitmessagefile)
  1575.         mymsg=open(commitmessagefile,"w")
  1576.         mymsg.write(commitmessage)
  1577.         mymsg.close()
  1578.  
  1579.         print
  1580.         print green("Using commit message:")
  1581.         print green("------------------------------------------------------------------------------")
  1582.         print commitmessage
  1583.         print green("------------------------------------------------------------------------------")
  1584.         print
  1585.  
  1586.         retval = None
  1587.         if "--pretend" in myoptions:
  1588.             print "(/usr/bin/cvs -q commit -F "+ commitmessagefile +" "+ string.join(myupdates," ")+")"
  1589.         else:
  1590.             retval=os.system("/usr/bin/cvs -q commit -F "+ commitmessagefile + " " +string.join(myupdates, " "))
  1591.             if retval:
  1592.                 print "!!! Exiting on cvs (shell) error code:",retval
  1593.                 sys.exit(retval)
  1594.  
  1595.     # Setup the GPG commands
  1596.     def gpgsign(filename):
  1597.         if "PORTAGE_GPG_KEY" not in repoman_settings:
  1598.             raise portage_exception.MissingParameter("PORTAGE_GPG_KEY is unset!")
  1599.         if "PORTAGE_GPG_DIR" not in repoman_settings:
  1600.             if os.environ.has_key("HOME"):
  1601.                 repoman_settings["PORTAGE_GPG_DIR"] = os.path.join(os.environ["HOME"], ".gnupg")
  1602.                 if quiet < 1:
  1603.                     print "Automatically setting PORTAGE_GPG_DIR to",repoman_settings["PORTAGE_GPG_DIR"]
  1604.             else:
  1605.                 raise portage_exception.MissingParameter("PORTAGE_GPG_DIR is unset!")
  1606.         gpg_dir = repoman_settings["PORTAGE_GPG_DIR"]
  1607.         if gpg_dir.startswith("~") and "HOME" in os.environ:
  1608.             repoman_settings["PORTAGE_GPG_DIR"] = os.path.join(
  1609.                 os.environ["HOME"], gpg_dir[1:].lstrip(os.path.sep))
  1610.         if not os.access(repoman_settings["PORTAGE_GPG_DIR"], os.X_OK):
  1611.             raise portage_exception.InvalidLocation(
  1612.                 "Unable to access directory: PORTAGE_GPG_DIR='%s'" % \
  1613.                 repoman_settings["PORTAGE_GPG_DIR"])
  1614.         gpgcmd = "gpg --sign --clearsign --yes "
  1615.         gpgcmd+= "--default-key "+repoman_settings["PORTAGE_GPG_KEY"]
  1616.         if repoman_settings.has_key("PORTAGE_GPG_DIR"):
  1617.             gpgcmd += " --homedir "+repoman_settings["PORTAGE_GPG_DIR"]
  1618.         if "--pretend" in myoptions:
  1619.             print "("+gpgcmd+" "+filename+")"
  1620.         else:
  1621.             rValue = os.system(gpgcmd+" "+filename)
  1622.             if rValue == os.EX_OK:
  1623.                 os.rename(filename+".asc", filename)
  1624.             else:
  1625.                 raise portage_exception.PortageException("!!! gpg exited with '" + str(rValue) + "' status")
  1626.  
  1627.     need_commit = False
  1628.     if myheaders or myupdates or myremoved or mynew:
  1629.         myfiles=myheaders+myupdates+myremoved+mynew
  1630.         for x in range(len(myfiles)-1, -1, -1):
  1631.             if myfiles[x].count("/") < 4-repolevel:
  1632.                 del myfiles[x]
  1633.         mydone=[]
  1634.         if repolevel==3:   # In a package dir
  1635.             repoman_settings["O"]=os.getcwd()
  1636.             portage.digestgen([], repoman_settings, manifestonly=1, myportdb=portage.portdb)
  1637.         elif repolevel==2: # In a category dir
  1638.             for x in myfiles:
  1639.                 xs=string.split(x,"/")
  1640.                 if xs[0]==".":
  1641.                     xs=xs[1:]
  1642.                 if xs[0] in mydone:
  1643.                     continue
  1644.                 mydone.append(xs[0])
  1645.                 repoman_settings["O"]=os.path.join(os.getcwd(), xs[0])
  1646.                 portage.digestgen([], repoman_settings, manifestonly=1, myportdb=portage.portdb)
  1647.         elif repolevel==1: # repo-cvsroot
  1648.             print green("RepoMan sez:"), "\"You're rather crazy... doing the entire repository.\"\n"
  1649.             for x in myfiles:
  1650.                 xs=string.split(x,"/")
  1651.                 if xs[0]==".":
  1652.                     xs=xs[1:]
  1653.                 if string.join(xs[:2],"/") in mydone:
  1654.                     continue
  1655.                 mydone.append(string.join(xs[:2],"/"))
  1656.                 repoman_settings["O"]=os.path.join(os.getcwd(), x[0], x[1])
  1657.                 portage.digestgen([], repoman_settings, manifestonly=1, myportdb=portage.portdb)
  1658.         else:
  1659.             print red("I'm confused... I don't know where I am!")
  1660.             sys.exit(1)
  1661.  
  1662.         # Force an unsigned commit when more than one Manifest needs to be signed.
  1663.         if repolevel < 3 and "sign" in repoman_settings.features:
  1664.             if "--pretend" in myoptions:
  1665.                 print "(/usr/bin/cvs -q commit -F "+commitmessagefile+")"
  1666.             else:
  1667.                 mymsg=open(commitmessagefile,"w")
  1668.                 mymsg.write(commitmessage)
  1669.                 mymsg.write("\n (Unsigned Manifest commit)")
  1670.                 mymsg.close()
  1671.                 retval=os.system("/usr/bin/cvs -q commit -F "+commitmessagefile)
  1672.                 if retval:
  1673.                     print "!!! Exiting on cvs (shell) error code:",retval
  1674.                     sys.exit(retval)
  1675.         else:
  1676.             need_commit = True
  1677.  
  1678.     signed = False
  1679.     if "sign" in repoman_settings.features:
  1680.         signed = True
  1681.         try:
  1682.             if repolevel==3:   # In a package dir
  1683.                 repoman_settings["O"] = "."
  1684.                 gpgsign(os.path.join(repoman_settings["O"], "Manifest"))
  1685.             elif repolevel==2: # In a category dir
  1686.                 mydone=[]
  1687.                 for x in myfiles:
  1688.                     xs=string.split(x,"/")
  1689.                     if xs[0]==".":
  1690.                         xs=xs[1:]
  1691.                     if xs[0] in mydone:
  1692.                         continue
  1693.                     mydone.append(xs[0])
  1694.                     repoman_settings["O"] = os.path.join(".", xs[0])
  1695.                     gpgsign(os.path.join(repoman_settings["O"], "Manifest"))
  1696.             elif repolevel==1: # repo-cvsroot
  1697.                 print green("RepoMan sez:"), "\"You're rather crazy... doing the entire repository.\"\n"
  1698.                 mydone=[]
  1699.                 for x in myfiles:
  1700.                     xs=string.split(x,"/")
  1701.                     if xs[0]==".":
  1702.                         xs=xs[1:]
  1703.                     if string.join(xs[:2],"/") in mydone:
  1704.                         continue
  1705.                     mydone.append(string.join(xs[:2],"/"))
  1706.                     repoman_settings["O"] = os.path.join(".", xs[0], xs[1])
  1707.                     gpgsign(os.path.join(repoman_settings["O"], "Manifest"))
  1708.         except portage_exception.PortageException, e:
  1709.             portage.writemsg("!!! %s\n" % str(e))
  1710.             portage.writemsg("!!! Disabled FEATURES='sign'\n")
  1711.             signed = False
  1712.  
  1713.     if need_commit or signed:
  1714.         if "--pretend" in myoptions:
  1715.             print "(/usr/bin/cvs -q commit -F "+commitmessagefile+")"
  1716.         else:
  1717.             mymsg=open(commitmessagefile,"w")
  1718.             mymsg.write(commitmessage)
  1719.             if signed:
  1720.                 mymsg.write("\n (Signed Manifest commit)")
  1721.             else:
  1722.                 mymsg.write("\n (Unsigned Manifest commit)")
  1723.             mymsg.close()
  1724.             retval=os.system("/usr/bin/cvs -q commit -F "+commitmessagefile)
  1725.             if retval:
  1726.                 print "!!! Exiting on cvs (shell) error code:",retval
  1727.                 sys.exit(retval)
  1728.  
  1729.     if unlinkfile:
  1730.         os.unlink(commitmessagefile)
  1731.     print
  1732.     if isCvs:
  1733.         print "CVS commit complete."
  1734.     else:
  1735.         print "repoman was too scared by not seeing any familiar cvs file that he forgot to commit anything"
  1736.     print green("RepoMan sez:"), "\"If everyone were like you, I'd be out of business!\"\n"
  1737. sys.exit(0)
  1738.  
  1739.